
#coding:utf-8

"""
CopyRight(c)  2017-09-15  Fraplus Corp

Author: Weilin Shen, Xiaodong.yang
Email:  xiaodong.yang@unidt.com
Functions:

we chat server

dependence package:

fralog
handler

# 安装依赖库
pip install rq
"""
import json
import os
from redis import Redis
from rq import Queue
from fralog.FraLog import Fralog
import requests
from globalsettings import CUR_MODE
if CUR_MODE == 'dev':
    from globalsettings_dev import *
else:
    from globalsettings_prod import *
log = Fralog().getFileLog()
log = Fralog().getFileLog()

face_dir = '/home/fra/survey/head/img'


def down_head(data):
    """
    需要并行执行的函数
    :param data: 
    :return: 
    """
    url = data['headimgurl']
    openid = data['openid']
    filename = '%s/%s.jpg' % (face_dir, openid)
    log.info(filename)
    try:
        f = open(filename, 'wb')
        r = requests.get(url)
        f.write(r.content)
        f.close()
    except Exception:
        log.error('下载头像出现故障')


class DownHead(object):
    inst = None

    def __init__(self):
        if REDIS_PASS is None or REDIS_PASS == '':
            self.rds = Redis(host=REDIS_IP, port=REDIS_PORT, db=0)
        else:
            self.rds = Redis(host=REDIS_IP, port=REDIS_PORT, password=REDIS_PASS, db=0)
        self.queue = Queue(connection = self.rds, name='wechat')
        self.jobs = []
        #
        # 实际执行的任务
        self.task = down_head

    def addJob(self, data):
        """
        添加下载图片任务
        :param data: 
        :return: 
        """
        openid = data['openid']
        if self.rds.get(openid) is not None:
            # log.warn('图片已经下载，不必重新下载')
            return
            # pass
        log.info('下载图片，昵称: %s'%(data['nickname']))
        self.rds.set(openid,'1')
        # log.info('add job')
        job = self.queue.enqueue(self.task, data)
        self.jobs.append(job)
    @staticmethod
    def instance():
        if DownHead.inst is None:
            log.info('instance.....')
            DownHead.inst = DownHead()
        return DownHead.inst


if __name__ == '__main__':
    url = 'http://wx.qlogo.cn/mmopen/vi_32/DYAIOgq83eoA2XiapDhpzKFM8f7SjNw3eoK2anTHAajvQeDSeXzT2C0WzdFJQpzCQtuLfAtpK79pSSM9waMachg/0'
    r = requests.get(url)
    print(r.encoding)
    f = open('1.jpg','wb')
    f.write(r.content)
    f.close()
